package com.dm0858.bianmin.mine.network;

import com.alibaba.fastjson.JSON;
import com.dm0858.bianmin.api.ApiService;
import com.dm0858.bianmin.mine.tools.LogUtils;
import com.dm0858.bianmin.mine.tools.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.util.LogUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import static com.dm0858.bianmin.app.ApiConstant.BASE_SERVER_URL;

/**
 * @author 迪迪丶Sir
 * @description 网络请求工具类
 * @e-mail asd969709719@qq.com
 * @since 2020-03-16
 **/
public class Retrofit {

    private static final int SUCCESS_CODE = 10000;
    private static final int ERROR_CODE = 10001;

    //请求的url
    private String url;
    //数据
    private HashMap<String, Object> map;
    //请求结果
    private String status;
    //请求返回的信息
    private String msg;
    //请求返回的数据
    private String data;
    private RetrofitListener listener;



    /**
     * @param
     * @return
     * @methodName
     * @description 设置url，清除map
     * @author 迪迪丶Sir
     * @since 2020-03-16
     **/
    public Retrofit url(final String url) {
        if (map == null) map = new HashMap<>();
        else map.clear();
        this.url = url;
        return this;
    }

    public Retrofit addParam(String key, Object value) {
        map.put(key, value);
        return this;
    }


    /**
     * @param
     * @return
     * @methodName
     * @description post请求
     * @author 迪迪丶Sir
     * @since 2020-03-16
     **/
    public void post(final RetrofitListener listener) {
        this.listener = listener;
        StringBuffer data = new StringBuffer();
        if (map != null && map.size() > 0) {
            Iterator iter = map.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                data.append(key).append("=").append(val).append("&");
            }
        }
        String json = data.substring(0, data.length() - 1);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"), json);
        LogUtils.v(json);
        NetworkManager.getRequest()
                .post(url, requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            processData(responseBody.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * @description 解析数据
     * @author 迪迪丶Sir
     * @e-mail asd969709719@qq.com
     * @since 2020-03-31
     **/

    private void processData(String s) {
        if (s.length() == 0) return;
        LogUtils.d(s);
        try {
            JSONObject jsonObject = new JSONObject(s);
            status = jsonObject.getString("status");
            data = jsonObject.getString("data");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        switch (status) {
            case "0":
                listener.onError(0,data);
                break;
            case "1":
                listener.onSuccess(data);
                break;
            case "-1":
                listener.onSuccess(data);
                break;
            default:
                ToastUtils.showShort("网络异常");
                break;
        }
    }
}
